import { Provide } from '@midwayjs/core';
import { ServicesImpl } from '../impl';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { TreeRepository } from 'typeorm';
import { Area } from '../../model/area/area';
import { AreaSchema } from '../../schema';
import { isNotEmpty } from '../../utils/isHelper';

@Provide()
export class AreaService extends ServicesImpl {
  /**
   * 覆盖实体
   */
  @InjectEntityModel(Area)
  services: TreeRepository<Area>;

  /**
   * 重写关系
   */
  relations: Array<string>;

  constructor() {
    super();
    this.relations = ['parent'];
  }
  async trees() {
    return await this.services.findTrees({ relations: this.relations });
  }

  async save(params: AreaSchema) {
    if (isNotEmpty(params.parent)) {
      const parent = await this.services.findOne({
        where: { id: params.parent?.id },
      });
      if (isNotEmpty(parent)) {
        Object.assign(params, { parent: parent });
      }
    }
    return await this.services.save(params);
  }

  async findByParent(parent) {
    if (isNotEmpty(parent.id)) {
      return await this.findMoreByFields({ parent });
    } else {
      return await this.services.findRoots();
    }
  }
}
